package com.teen9g.infoplatformserver.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.teen9g.constant.CategoryConstant;
import com.teen9g.constant.RedisKey;
import com.teen9g.context.BaseContext;
import com.teen9g.dto.TeachingBuildingDTO;
import com.teen9g.entity.SingleRecentEdit;
import com.teen9g.entity.TeachingBuilding;
import com.teen9g.infoplatformserver.mapper.RecentEditMapper;
import com.teen9g.infoplatformserver.mapper.TeachingBuildingMapper;
import com.teen9g.infoplatformserver.service.TeachingBuildingService;
import com.teen9g.userVO.TeachingBuildingUserVO;
import com.teen9g.utils.StringUtil;
import org.codehaus.jettison.json.JSONException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class TeachingBuildingServiceImpl
        extends ServiceImpl<TeachingBuildingMapper, TeachingBuilding>
        implements TeachingBuildingService {

    @Autowired
    private TeachingBuildingMapper teachingBuildingMapper;

    @Autowired
    private RecentEditMapper recentEditMapper;

    @Autowired
    private RedisTemplate<String, Long> redisTemplate;
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 添加教学楼信息
     *
     * @param teachingBuildingDTO 教学楼信息DTO
     * @return 添加结果
     */
    @Override
    public int add(TeachingBuildingDTO teachingBuildingDTO) {
        TeachingBuilding teachingBuilding = TeachingBuilding.builder()
                .buildingId(teachingBuildingDTO.getBuildingId())
                .buildingName(teachingBuildingDTO.getBuildingName())
                .roomNumber(teachingBuildingDTO.getRoomNumber())
                .contentTitle(teachingBuildingDTO.getContentTitle())
                .contentDescription(teachingBuildingDTO.getContentDescription())
                .contentImage(teachingBuildingDTO.getContentImage())
                .build();
        String currentUser = BaseContext.getCurrentUser();
        if (currentUser == null) {
            return -1;
        }
        teachingBuilding.setContentAuthor(currentUser);
        teachingBuilding.setContentRecentEditor(currentUser);
        teachingBuilding.setContentCreateTime(LocalDateTime.now());
        teachingBuilding.setContentUpdateTime(LocalDateTime.now());
        return teachingBuildingMapper.insert(teachingBuilding);
    }


    /**
     * 根据id获取教学楼信息
     *
     * @param id 教学楼信息id
     * @return 教学楼信息
     */
    @Override
    public TeachingBuilding getById(Integer id) {
        return teachingBuildingMapper.selectById(id);
    }

    /**
     * 修改教学楼信息
     *
     * @param teachingBuildingDTO 前端传来的修改内容
     * @param id                  教学楼信息id
     * @return 修改结果 若为-1则为修改失败 1为修改成功，999为前后没有变化
     */
    @Override
    public int update(TeachingBuildingDTO teachingBuildingDTO, Integer id) throws JSONException {
        //先判断传入的对象是否为空
        if (teachingBuildingDTO.getBuildingId() == null) {
            return -1;
        }
        //先获取原实体，判断原实体是否存在
        TeachingBuilding teachingBuilding =
                teachingBuildingMapper.selectById(id);
        if (teachingBuilding == null) {
            return -1;
        }
        //判断前后是否更新，如果没有更新则返回999
        TeachingBuildingDTO tempDTO = new TeachingBuildingDTO();
        BeanUtils.copyProperties(teachingBuilding, tempDTO);
        if (teachingBuildingDTO.equals(tempDTO)) {
            return 999;
        }
        //判断进行更新了则生成修改内容
        StringUtil stringUtil = new StringUtil();
        String operation = stringUtil.TB_getOperation(tempDTO, teachingBuildingDTO);

        if (!operation.isEmpty()) {
            //先插入一条编辑记录
            SingleRecentEdit singleRecentEdit = SingleRecentEdit.builder()
                    .updateEditor(BaseContext.getCurrentUser())
                    .updateTime(LocalDateTime.now())
                    .contentCategory(CategoryConstant.TEACHING_BUILDING)
                    .contentId(id)
                    .contentTitle(teachingBuildingDTO.getContentTitle())
                    .updateOperation(operation)
                    .build();
            recentEditMapper.insert(singleRecentEdit);
        }

        //修改教学楼信息
        BeanUtils.copyProperties(teachingBuildingDTO, teachingBuilding);
        teachingBuilding.setContentRecentEditor(BaseContext.getCurrentUser());
        teachingBuilding.setContentUpdateTime(LocalDateTime.now());
        int updateResult = teachingBuildingMapper.updateById(teachingBuilding);
        if (updateResult == 1) {
            return 1; // 更新成功
        } else {
            return -1; // 更新失败
        }
    }

    /**
     * 根据id删除教学楼信息
     *
     * @param id 教学楼信息id
     * @return 删除结果
     */
    @Override
    public int delete(Integer id) {
        //判断删除者是否为内容原作者
        TeachingBuilding teachingBuilding = teachingBuildingMapper.selectById(id);
        if (!BaseContext.getCurrentUser().equals(teachingBuilding.getContentAuthor())) {
            return -1;
        }
        return teachingBuildingMapper.deleteById(id);
    }


    @Override
    public PageInfo<TeachingBuilding> getpage
            (Integer pageNum, Integer pageSize, Integer buildingId, String roomNumber) {

        //开始分页
        PageHelper.startPage(pageNum, pageSize);
        //根据参数查询
        List<TeachingBuilding> list = teachingBuildingMapper.getpage(buildingId, roomNumber);
        // 使用pageInfo包装查询后的结果，封装了详细的查询数据
        return new PageInfo<>(list);
    }

    @Override
    public void addView(Integer id) {
        redisTemplate.opsForValue().increment(RedisKey.TB_VIEW_KEY + id);
    }

    @Override
    public PageInfo<TeachingBuildingUserVO>
    getpageUser(Integer pageNum, Integer pageSize, String contentAuthor) {

        PageHelper.startPage(pageNum, pageSize);
        List<TeachingBuildingUserVO> list = teachingBuildingMapper.getpageUser(contentAuthor);
        for (TeachingBuildingUserVO teachingBuildingUserVO : list) {
            if (teachingBuildingUserVO.getContentImage() != null) {
                //提取出图片的第一张用于展示
                try {
                    String[] imageList = objectMapper.readValue(teachingBuildingUserVO.getContentImage(), String[].class);
                    if (imageList.length > 0) {
                        teachingBuildingUserVO.setContentImage(imageList[0]);
                    }
                } catch (JsonProcessingException e) {
                    throw new RuntimeException(e);
                }
            }
        }
        return new PageInfo<>(list);
    }
}
